<template>
  <div class="mutual page">
    <div class="tab-area">
      <div class="header-actions">
        <div class="tabs-wrapper">
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="创建时间" name="0"></el-tab-pane>
            <el-tab-pane label="名称查询" name="9"></el-tab-pane>
            <el-tab-pane label="热门" name="1"></el-tab-pane>
            <el-tab-pane label="最多点赞" name="2"></el-tab-pane>
            <el-tab-pane label="最多收藏" name="3"></el-tab-pane>
            <el-tab-pane label="最多转发" name="4"></el-tab-pane>
            <el-tab-pane label="最多参与" name="5"></el-tab-pane>
            <el-tab-pane label="领域匹配" name="6"></el-tab-pane>
          </el-tabs>
        </div>
      </div>
      
      <div class="content-list">
        <div class="mutual-list">
          <el-card 
            v-for="item in mutualList" 
            :key="item.id"
            class="mutual-item"
            shadow="hover"
          >
            <div class="join-badge" v-if="item.registrationStatus === '1'">
              <img :src="require('@/assets/img/join.png')" alt="已参与" />
            </div>
            <div class="item-content">
              <div class="main-info" @click="goToDetail(item)">
                <div class="title-area">
                  <h3 class="title">{{ item.title }}</h3>
                  <el-tag 
                    v-if="item.priorityField"
                    size="small"
                    type="info">{{ item.priorityField }}</el-tag>
                </div>
                <div class="publisher-info">
                  <span class="publisher">
                    <i class="el-icon-user"></i>
                    {{ item.publisherName }}
                  </span>
                  <el-tooltip 
                    :content="item.currentResidence" 
                    placement="top"
                    :disabled="!item.currentResidence || item.currentResidence.length <= 3"
                  >
                    <span class="location">
                      <i class="el-icon-location"></i>
                      {{ formatAddress(item.currentResidence) }}
                    </span>
                  </el-tooltip>
                  <span class="date">
                    <i class="el-icon-time"></i>
                    {{ formatDate(item.createTime) }}
                  </span>
                </div>
              </div>
              
              <div class="participation-row" v-if="item.registrationCount > 0">
                <i class="el-icon-user"></i>
                <span>{{ item.registrationCount }}人参与</span>
              </div>
              
              <div class="item-info">
                <div class="info-item">
                  <i class="el-icon-hot-water"></i>
                  <span>{{ item.heatValue }}</span>
                </div>
                <div class="info-item" 
                     :class="{ 'is-active': item.likeStatus === '1' }">
                  <img :src="require(`@/assets/img/${item.likeStatus === '1' ? 'good1' : 'good'}.png`)" 
                       class="icon-img" 
                       alt="点赞">
                  <span>{{ item.likeCount }}</span>
                </div>
                <div class="info-item" 
                     :class="{ 'is-active': item.collectionStatus === '1' }">
                  <img :src="require(`@/assets/img/${item.collectionStatus === '1' ? 'collection1' : 'collection'}.png`)" 
                       class="icon-img" 
                       alt="收藏">
                  <span>{{ item.collectionCount }}</span>
                </div>
                <div class="info-item">
                  <i class="el-icon-share"></i>
                  <span>{{ item.forwardCount }}</span>
                </div>
                <div class="info-item report-btn" @click.stop="handleReport(item)">
                  <img src="@/assets/img/report.png" alt="举报" class="icon-img" />
                </div>
              </div>
            </div>
          </el-card>

          <!-- 分页器 -->
          <div class="load-more" v-if="mutualList.length > 0">
            <el-pagination
              background
              layout="prev, pager, next"
              :total="total"
              :current-page.sync="currentPage"
              :page-size="pageSize"
              @current-change="handlePageChange"
            >
            </el-pagination>
          </div>

          <!-- 空状态 -->
          <el-empty
            v-if="mutualList.length === 0"
            description="暂无合作信息">
          </el-empty>
        </div>
      </div>
    </div>

    <!-- 添加悬浮按钮 -->
    <div class="floating-button">
      <el-button 
        type="primary" 
        icon="el-icon-plus"
        round
        size="medium"
        @click="goToCreate"
      >发起合作</el-button>
    </div>

    <!-- 举报弹框 -->
    <el-dialog
      title="举报合作"
      :visible.sync="reportVisible"
      width="90%"
      :show-close="false"
      custom-class="report-dialog"
    >
      <el-form>
        <el-form-item>
          <el-input
            type="textarea"
            v-model="reportContent"
            :rows="4"
            :maxlength="200"
            placeholder="请输入举报原因..."
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reportVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReport" :loading="submitting">
          提 交
        </el-button>
      </div>
    </el-dialog>

    <!-- 添加搜索弹窗 -->
    <el-dialog
      title="合作名称查询"
      :visible.sync="searchDialogVisible"
      width="90%"
      custom-class="search-dialog"
      :close-on-click-modal="false"
      :show-close="true"
      @close="handleSearchCancel"
    >
      <el-form :model="searchForm" ref="searchForm" :rules="searchRules">
        <el-form-item prop="keyword">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入合作名称关键字"
            clearable
            prefix-icon="el-icon-search"
            class="search-input"
          >
            <template slot="append">
              <el-button 
                type="primary"
                @click="handleSearch"
                :loading="loading"
              >
                查询
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { alumniMutualList, alumniMutualLike, activityHandleCollection } from "@/api/api";

export default {
  name: "Mutual",
  data() {
    return {
      activeTab: '0',  // 修改默认选中为创建时间
      mutualList: [],
      loading: false,
      total: 0,
      currentPage: 1,
      pageSize: 5,
      reportVisible: false,
      reportContent: '',
      submitting: false,
      currentItem: null,
      searchDialogVisible: false,
      searchForm: {
        keyword: ''
      },
      searchRules: {
        keyword: [
          { required: true, message: '请输入查询关键字', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      },
      hasSearched: false, // 添加标记，用于判断是否执行过查询
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    formatDate(date) {
      if (!date) return '';
      const dt = new Date(date);
      
      const year = dt.getFullYear();
      const month = String(dt.getMonth() + 1).padStart(2, '0');
      const day = String(dt.getDate()).padStart(2, '0');
      
      return `${year}-${month}-${day}`;
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.loadData()
    },
    handleTabClick() {
      this.currentPage = 1;  // 切换标签时重置页码
      if (this.activeTab === '9') {
        // 如果是名称查询标签，显示搜索弹窗，不立即加载数据
        this.searchDialogVisible = true;
        this.searchForm.keyword = ''; // 清空搜索关键字
      } else {
        // 其他标签正常加载数据
        this.loadData();
      }
    },
    async loadData() {
      try {
        this.loading = true;
        const params = {
          sortType: this.activeTab,
          pageNum: this.currentPage.toString(),
          pageSize: this.pageSize.toString()
        };

        // 如果是名称查询，添加title参数
        if (this.activeTab === '9' && this.searchForm.keyword) {
          params.title = this.searchForm.keyword;
          this.hasSearched = true; // 标记已经执行过查询
        }

        const res = await alumniMutualList(params);
        
        if (res.success) {
          this.mutualList = res.data.records;
          this.total = res.data.total;
        }
      } catch (error) {
        this.$message.error('加载失败');
      } finally {
        this.loading = false;
      }
    },
    async handleLike(item) {
      try {
        const params = { id: item.id }
        const res = await alumniMutualLike(params)
        
        if (res.success) {
          item.likeStatus = item.likeStatus === '1' ? '0' : '1'
          item.likeCount = item.likeStatus === '1' 
            ? Number(item.likeCount || 0) + 1 
            : Math.max(0, Number(item.likeCount || 0) - 1)
            
          this.$message({
            type: 'success',
            message: item.likeStatus === '1' ? '点赞成功' : '取消点赞成功'
          })
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    async handleCollect(item) {
      try {
        const params = { id: item.id }
        const res = await activityHandleCollection(params)
        
        if (res.success) {
          item.collectionStatus = item.collectionStatus === '1' ? '0' : '1'
          item.collectionCount = item.collectionStatus === '1'
            ? Number(item.collectionCount || 0) + 1
            : Math.max(0, Number(item.collectionCount || 0) - 1)
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    formatAddress(address) {
      if (!address) return '';
      return address.length > 3 ? address.substring(0, 3) + '...' : address;
    },
    goToDetail(item) {
      this.$router.push({
        path: '/mutual/details',
        query: { id: item.id }
      });
    },
    goToCreate() {
      this.$router.push('/mutual/create');
    },
    handleReport(item) {
      this.currentItem = item;
      this.reportVisible = true;
      this.reportContent = '';
    },
    async submitReport() {
      if (!this.reportContent.trim()) {
        this.$message.warning('请输入举报原因');
        return;
      }
      
      try {
        this.submitting = true;
        // 模拟提交延迟
        setTimeout(() => {
          this.reportVisible = false;
          this.$message({
            type: 'success',
            message: '举报已提交，我们会尽快处理',
            duration: 3000
          });
        }, 500);
      } catch (error) {
        this.$message.error('提交失败，请稍后重试');
      } finally {
        this.submitting = false;
      }
    },
    async handleSearch() {
      try {
        await this.$refs.searchForm.validate();
        this.currentPage = 1; // 重置页码
        await this.loadData();
        this.searchDialogVisible = false;
      } catch (error) {
        // 表单验证失败
        return;
      }
    },
    handleSearchCancel() {
      this.searchDialogVisible = false;
      this.searchForm.keyword = '';
      // 如果没有执行过查询，切回默认标签
      if (!this.hasSearched) {
        this.activeTab = '0';
      }
    }
  },
  watch: {
    // 移除 activeTab 的 watch
  }
}
</script>

<style lang="less" scoped>
.mutual {
  min-height: 100vh;
  background: linear-gradient(180deg, rgba(255, 192, 203, 0.1) 0%, rgba(255, 182, 193, 0.05) 50%, rgba(255, 255, 255, 0.8) 100%);

  .mutual-list {
    padding: 16px;
    position: relative;
    min-height: 200px;

    .mutual-item {
      margin-bottom: 16px;
      border-radius: 8px;
      transition: all 0.3s ease;
      position: relative;
      box-shadow: 0 2px 12px 0 rgba(255, 182, 193, 0.15);
      background: rgba(255, 255, 255, 0.9);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px 0 rgba(255, 182, 193, 0.2);
      }

      .join-badge {
        position: absolute;
        top: -2px;
        left: -2px;
        z-index: 1;
        
        img {
          width: 50px;
          height: 50px;
          object-fit: contain;
        }
      }

      .item-content {
        .main-info {
          .title-area {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 12px;
            margin-left: 40px;

            .title {
              font-size: 16px;
              font-weight: 500;
              color: #333;
              margin: 0;
              &:hover {
                color: #FF69B4;
              }
            }
          }

          .publisher-info {
            display: flex;
            gap: 16px;
            color: #999;
            font-size: 13px;
            margin-bottom: 12px;

            span {
              display: flex;
              align-items: center;
              gap: 4px;
              i {
                color: #FFB6C1;
              }
            }

            .location {
              cursor: default;
              
              &:hover {
                color: inherit;
              }
            }
          }
        }

        .participation-row {
          display: flex;
          align-items: center;
          gap: 4px;
          padding: 8px 0;
          color: #FF69B4;
          font-size: 13px;
          border-top: 1px dashed #eee;
          margin: 8px 0;

          i {
            font-size: 14px;
          }
        }

        .item-info {
          display: flex;
          gap: 16px;
          padding-top: 12px;
          border-top: 1px solid #eee;

          .info-item {
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 4px 8px;
            border-radius: 4px;
            transition: all 0.3s ease;

            &:hover {
              background-color: rgba(255, 182, 193, 0.1);
              color: #FF69B4;
            }

            &.is-active {
              color: #FF69B4;
              background-color: rgba(255, 182, 193, 0.15);
            }
            
            .icon-img {
              width: 16px;
              height: 16px;
              object-fit: contain;
            }

            span {
              font-size: 13px;
            }
          }

          .report-btn {
            margin-left: auto;
            
            &:hover {
              color: #F56C6C;
              background-color: rgba(245, 108, 108, 0.1);
            }
          }
        }
      }
    }
  }

  .tab-area {
    background: rgba(255, 182, 193, 0.1);
    padding: 15px 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(255, 182, 193, 0.15);
    overflow: hidden;

    .header-actions {
      .tabs-wrapper {
        overflow-x: auto;
        overflow-y: hidden;
        -webkit-overflow-scrolling: touch;
        
        &::-webkit-scrollbar {
          display: none;
        }
        -ms-overflow-style: none;
        scrollbar-width: none;

        :deep(.el-tabs) {
          .el-tabs__nav-wrap {
            &::after {
              height: 1px;
              background-color: rgba(255, 182, 193, 0.2);
            }
          }

          .el-tabs__header {
            margin: 0;
          }

          .el-tabs__nav {
            white-space: nowrap;
            float: none;
          }
        }
      }
    }
  }
  
  .content-list {
    margin-top: 20px;
    min-height: 200px;
  }

  .load-more {
    text-align: center;
    margin-top: 20px;
    padding: 10px 0;
  }

  // 添加悬浮按钮样式
  .floating-button {
    position: fixed;
    right: 20px;
    bottom: 80px;
    z-index: 1000;

    .el-button {
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
      padding: 12px 24px;
      
      &:hover {
        transform: translateY(-2px);
        transition: all 0.3s ease;
        box-shadow: 0 4px 12px 0 rgba(0,0,0,0.15);
      }
    }
  }
}

:deep(.el-pagination.is-background) {
  .el-pager li:not(.disabled).active {
    background-color: #FF69B4;
  }
  .el-pager li:not(.disabled):hover {
    color: #FF69B4;
  }
}

@media screen and (max-width: 768px) {
  .mutual-list {
    .mutual-item {
      .join-badge {
        img {
          width: 40px;
          height: 40px;
        }
      }
      
      .main-info .title-area {
        margin-left: 30px;
      }
    }
  }
}

.report-dialog {
  /deep/ .el-dialog__body {
    padding: 20px;
  }
  
  /deep/ .el-textarea__inner {
    background: #f7fafd;
    border: none;
    border-radius: 8px;
    padding: 15px;
    font-size: 14px;
    
    &::placeholder {
      color: #999;
    }
  }
  
  .dialog-footer {
    text-align: center;
    padding-top: 10px;
  }
}

@media screen and (max-width: 768px) {
  .report-dialog {
    /deep/ .el-dialog {
      width: 90% !important;
      margin-top: 20vh !important;
    }
  }
}

// 添加搜索弹窗样式
.search-dialog {
  /deep/ .el-dialog {
    border-radius: 12px;
    overflow: hidden;
    background: rgba(255, 182, 193, 0.1);
    backdrop-filter: blur(10px);
    box-shadow: 0 2px 12px 0 rgba(255, 182, 193, 0.2);
    
    .el-dialog__header {
      padding: 20px;
      background: rgba(255, 182, 193, 0.2);
      margin-right: 0;
      border-bottom: 1px solid rgba(255, 182, 193, 0.2);
      
      .el-dialog__title {
        font-size: 16px;
        font-weight: 500;
        color: #FF69B4;
      }
      
      .el-dialog__headerbtn .el-dialog__close {
        color: #606266;
        
        &:hover {
          color: #FF69B4;
        }
      }
    }
    
    .el-dialog__body {
      padding: 30px 20px;
      background: rgba(255, 182, 193, 0.05);
      
      .el-form-item {
        margin-bottom: 0;
        
        .search-input {
          /deep/ .el-input__inner {
            background: rgba(255, 255, 255, 0.9);
            border-color: rgba(255, 182, 193, 0.4);
            color: #FF69B4;
            
            &::placeholder {
              color: rgba(255, 182, 193, 0.6);
            }
            
            &:focus {
              border-color: #FF69B4;
              background: rgba(255, 255, 255, 0.95);
            }
          }
          
          /deep/ .el-input__prefix {
            .el-input__icon {
              color: rgba(255, 182, 193, 0.6);
            }
          }
          
          /deep/ .el-input-group__append {
            background: rgba(255, 255, 255, 0.9);
            border-color: rgba(255, 182, 193, 0.4);
            
            .el-button {
              color: #FF69B4;
              
              &:hover, &:focus {
                background-color: #FF69B4;
                border-color: #FF69B4;
                color: #fff;
              }
              
              &.is-loading {
                background-color: #FF69B4;
                border-color: #FF69B4;
                color: #fff;
              }
            }
          }
        }
      }
    }
  }
}
</style>